package storage.v1;

import java.io.IOException;
import java.util.Collection;

import com.onpositive.mediawiki.dataminer.IReferencesStorage;
import com.onpositive.wiki3.db.IRedirectAccess;
import com.onpositive.wiki3.db.ITextContentAccess;
import com.onpositive.wiki3.db.ITitleMapper;
import com.onpositive.wiki3.db.IWikiDB;
import com.onpositive.wiki3.db.SimpleReconciler;

public class DBStorage implements IReferencesStorage{

	IWikiDB content;
	IRedirectAccess d;
	ITextContentAccess m;
	
	private ITitleMapper tm;
	SimpleReconciler rc;
	
	public DBStorage(IWikiDB db) throws IOException{
		this.content=db;
		this.d=db.getRedirectAccess();
		this.m=db.getContentAccessor();
		this.tm=db.getTitleMapper();
		rc=new SimpleReconciler(db);
	}
	
	@Override
	public String getContent(String id, int flags) {
		int id2 = tm.getId(id);
		int redirect = d.getRedirect(id2);
		if (redirect!=-1){
			id2=redirect;
		}
		return m.getTextContent(id);
	}

	@Override
	public Collection<String> getChildren(String name) {
		int id2 = tm.getId(name.toLowerCase().replace(' ', '_'));
		Collection<String> sm=rc.getChildren(id2);
		return sm;
	}

	@Override
	public Collection<String> getParents(String name) {
		int id2 = tm.getId(name.toLowerCase().replace(' ', '_'));
		Collection<String> sm=rc.getParents(id2);
		if(sm==null)
			return null;
		
		if (sm.isEmpty()){
			id2 = tm.getId(name);
			sm=rc.getParents(id2);
		}
		return sm;
	}

	@Override
	public void saveStorage() {
		
	}
	
	public int size(){
		return tm.size();
	}
	
	public String getTitle(int id){
		return tm.getTitle(id);
	}

}
